package net.suncaper.demo.controller;


import net.suncaper.demo.domain.Employee;
import net.suncaper.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/employees")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;


    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String employeePage(Model model) {
        //TODO: Add Employee search result
        List<Employee> employees = employeeService.listEmployee();
        model.addAttribute("employees", employees);
        return "employee-list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addEmployeePage(Model model) {
        model.addAttribute("employee", new Employee());
        return "employee-add";
    }

    @GetMapping("/edit")
    public String editEmployeePage(@RequestParam("id") String id, Model model) {
        Employee employee = employeeService.findEmployeeByPrimaryKey(id);
        model.addAttribute("employee", employee);
        return "employee-add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String saveEmployee(Employee employee) {
        int updated = employeeService.saveEmployee(employee);
        return "redirect:/employees/search";
    }

    @DeleteMapping("/delete")
    @ResponseBody
    public Boolean deleteEmployee(@RequestParam("id") String id) {
        int deleted = employeeService.deleteEmployeeByPrimaryKey(id);

        return deleted > 0;
    }
}
